<?php

class SiteController extends Controller{

	public function accessRules(){
		return array(
				array('allow',
						'actions'=>array( 'index', 'error', 'login', 'logout' ),
						'users'=>array('*'),
				)
		);
	}
	
	public function filters(){
		return [ 'accessControl' ];
	}
	
	public function actionIndex(){
		$this->redirect( '/app/index.html' );
	}
	
	public function actionError(){
		if( $error=Yii::app()->errorHandler->error ){
			if( Yii::app()->request->isAjaxRequest )
				$this->renderJSON( $error['message'] ); 
			else
				$this->render( 'error', $error );
		}
	}
	
	public function actionInsert( $u, $p ){
		$user = new Users();
		$user->username = $u;
		$user->userHash = Crypt::generateHash( $p );
		$user->loginToken = Crypt::generateToken( $u );
		$user->save();
	}
	
	public function actionLogin( $username, $password ){
		$user = new UserIdentity( $username, $password );
		$user->authenticate();
		
		switch( $user->errorCode ){
			case $user::ERROR_USERNAME_INVALID:
				$error = [ 'error' => Yii::t( 'site', "Username doesn't exists" ) ];
				$this->renderJSON( $error );
				break;
			case $user::ERROR_PASSWORD_INVALID:
				$error = [ 'error' => Yii::t( 'site', 'Incorrect password' ) ];
				$this->renderJSON( $error );
				break;
			case $user::ERROR_NONE:
				Yii::app()->user->login( $user, 0 );
				$this->renderJSON( [ 'user' => [ 'loginToken' => Yii::app()->user->loginToken, 'idUser' => Yii::app()->user->id, 
						'username' => Yii::app()->user->username, 'userRole' => 'logged' ] ] );
				break;
		}

	}
	
	public function actionLogout(){
		Yii::app()->user->logout();
		$this->renderJSON( [ 'result' => '1' ] );
		//$this->redirect( Yii::app()->homeUrl );
	}
}